package com.herr.springboot.data.jdbc.service;

import com.herr.springboot.data.jdbc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Service
public class UserServiceImpl2  implements UserService {

    @Autowired
    private JdbcTemplate jdbcTemplateSecond;

    @Override
    public void create(String name, Integer age) {
        jdbcTemplateSecond.update("insert into user(user_name, age) values(?, ?)", name, age);
    }
    @Override
    public void deleteByName(String name) {
        jdbcTemplateSecond.update("delete from user where user_name = ?", name);
    }
    @Override
    public Integer getAllUsersCount() {
        return jdbcTemplateSecond.queryForObject("select count(1) from user", Integer.class);
    }
    @Override
    public void deleteAllUsers() {
        jdbcTemplateSecond.update("delete from user");
    }

    @Override
    public List<User> getAllUsers() {
        return jdbcTemplateSecond.query("select * from user", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                long id = resultSet.getLong("user_id");
                String username = resultSet.getString("user_name");
                String age = resultSet.getString("age");
                user.setUserName(username);
                user.setUserId(id);
                user.setAge(age);
                return user;
            }
        });
    }

    @Override
    public List<User> getAllUsers2() {
        return jdbcTemplateSecond.query("select * from user", new BeanPropertyRowMapper<>(User.class));
    }
}
